package xuegao.study.mall.admin.service.pms.impl;

import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import xuegao.study.mall.repo.dao.pms.*;
import xuegao.study.mall.common.model.pms.PmsProduct;
import xuegao.study.mall.common.model.pms.PmsSkuStock;
import xuegao.study.mall.common.param.pms.PmsProductParam;
import xuegao.study.mall.common.param.pms.PmsProductResult;
import xuegao.study.mall.admin.service.pms.PmsProductService;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PmsProductServiceImpl implements PmsProductService {

    private final Logger LOGGER = LoggerFactory.getLogger(PmsProductServiceImpl.class);

    @Autowired
    private PmsProductDao pmsProductDao;

    @Autowired
    private PmsMemberPriceDao pmsMemberPriceDao;

    @Autowired
    private PmsProductLadderDao pmsProductLadderDao;

    @Autowired
    private PmsProductFullReductionDao pmsProductFullReductionDao;

    @Autowired
    private PmsSkuStockDao pmsSkuStockDao;

    @Autowired
    private PmsProductAttributeValueDao pmsProductAttributeValueDao;

    @Override
    public List<PmsProduct> list(Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> params = new HashMap<>();
        params.put("delete_status", "0");
        return pmsProductDao.selectByMap(params);
    }

    @Override
    @Transactional
    public int create(PmsProductParam param) {
        int count;
        // 创建商品
        PmsProduct product = param;
        product.setId(null);
        pmsProductDao.insert(product);
        // 根据促销类型设置价格:会员价格 阶梯价格 满减价格
        Long productId = product.getId();
        // 会员价格
        relateAndInsert(pmsMemberPriceDao, param.getMemberPriceList(), productId);
        // 阶梯价格
        relateAndInsert(pmsProductLadderDao, param.getProductLadderList(), productId);
        // 满减价格
        relateAndInsert(pmsProductFullReductionDao, param.getProductFullReductionList(), productId);
        // 处理sku码并存储sku信息
        handleSkuStockCode(param.getSkuStockList(), productId);
        relateAndInsert(pmsSkuStockDao, param.getSkuStockList(), productId);
        // 添加商品参数
        relateAndInsert(pmsProductAttributeValueDao, param.getProductAttributeValueList(), productId);
        // todo
        // 关联专题

        // 关联优选
        count = 1;
        return count;
    }

    @Override
    @Transactional
    public int update(Long id, PmsProductParam param) {
        int count;
        // 更新商品信息
        PmsProduct product = param;
        product.setId(id);
        pmsProductDao.updateByPrimaryKeySelective(product);
        Long productId = id;
        // 会员价格
        Map<String, Object> deleteParams = new HashMap<>();
        deleteParams.put("product_id", id);
        pmsMemberPriceDao.deleteByMap(deleteParams);
        relateAndInsert(pmsMemberPriceDao, param.getMemberPriceList(), productId);
        // 阶梯价格
        pmsProductLadderDao.deleteByMap(deleteParams);
        relateAndInsert(pmsProductLadderDao, param.getProductLadderList(), productId);
        // 满减价格
        pmsProductFullReductionDao.deleteByMap(deleteParams);
        relateAndInsert(pmsProductFullReductionDao, param.getProductFullReductionList(), productId);
        // 修改sku库存信息
        handleUpdateSkuStockList(id, param);
        // 修改商品参数,添加自定义商品规格
        pmsProductAttributeValueDao.deleteByMap(deleteParams);
        relateAndInsert(pmsProductAttributeValueDao, param.getProductAttributeValueList(), productId);
        // todo 关联专题

        // todo 关联优选
        count = 1;
        return count;
    }

    private void handleUpdateSkuStockList(Long id, PmsProductParam productParam) {
        // todo
    }


    @Override
    public PmsProductResult getUpdateInfo(Long id) {
        return pmsProductDao.getUpdateInfo(id);
    }

    @Override
    public int delete(Long id) {
        return pmsProductDao.delPmsProduct(id);
    }

    private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
        if (CollectionUtils.isEmpty(skuStockList)) {
            return;
        }
        for (int i = 0; i < skuStockList.size(); i++) {
            PmsSkuStock skuStock = skuStockList.get(i);
            if (StringUtils.isEmpty(skuStock.getSkuCode())) {
                String skuCode = createSkuCode(i, productId);
                skuStock.setSkuCode(skuCode);
            }
        }
    }

    private String createSkuCode(int index, Long productId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        StringBuffer sb = new StringBuffer();
        // 日期
        sb.append(sdf.format(new Date()));
        // 四位商品id
        sb.append(String.format("%04d", productId));
        // 三位索引id
        sb.append(String.format("%03d", index + 1));
        return sb.toString();
    }

    private void relateAndInsert(Object dao, List dataList, Long product) {
        try {
            if (CollectionUtils.isEmpty(dataList)) {
                return;
            }
            for (Object item : dataList) {
                Method setIdM = item.getClass().getMethod("setId", Long.class);
                setIdM.invoke(item, (Long) null);
                Method setProductIdM = item.getClass().getMethod("setProductId", Long.class);
                setProductIdM.invoke(item, product);
            }
            Method insertM = dao.getClass().getMethod("insertList", List.class);
            insertM.invoke(dao, dataList);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
}
